package projet.volleystat;

import projet.volleystat.bdd.VolleyOpenhelper;
import projet.volleystat.bdd.VolleyRepository;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class AddAssociationActivity extends Activity {
	protected ListView listv;
	protected SimpleCursorAdapter cadapter;
	protected Cursor query;
	protected VolleyRepository volleyDataBase;
	int idteam;
	Team team;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_association);

		volleyDataBase = new VolleyRepository(getApplicationContext());
		volleyDataBase.open();

		Bundle bundle = getIntent().getExtras();
		idteam = bundle.getInt("id");

		try {
			team = volleyDataBase.getTeamById(idteam);
		} catch (DatabaseException e1) {
			e1.printStackTrace();
		}

		try {
			query = volleyDataBase.getAllCursorPlayerNotInTeam(team);
		} catch (DatabaseException e) {
			e.printStackTrace();
		}

		listv = (ListView) findViewById(R.id.addplayerlv);
		cadapter = new SimpleCursorAdapter(
				getApplicationContext(),
				R.layout.listitemlineplayer,
				query,
				new String[] { VolleyOpenhelper.Player_Columns_NAME,
						VolleyOpenhelper.Player_Columns_FIRSTNAME,
						VolleyOpenhelper.Player_Columns_NATIONALITY },
				new int[] { R.id.textname, R.id.textfirstname, R.id.textnation });
		listv.setAdapter(cadapter);

		listv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					volleyDataBase.associate(
							volleyDataBase.getPlayerById((int) id), team);
				} catch (DatabaseException e) {
					e.printStackTrace();
				}
				finish();
			}
		});
	}

	@Override
	public void onResume() {
		super.onResume();
		volleyDataBase.open();
		try {
			query = volleyDataBase.getAllCursorPlayerNotInTeam(team);
		} catch (DatabaseException e) {
			e.printStackTrace();
		}
		cadapter.changeCursor(query);
	}

	@Override
	public void onPause() {
		super.onPause();
		overridePendingTransition(0, 0);
		query.close();
		volleyDataBase.close();
	}
}
